package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"

	"gitee.com/krio/grpc-common/dao"
	"gitee.com/krio/grpc-common/model"
	"gitee.com/krio/grpc-common/util"
	pbCommon "gitee.com/krio/grpc-pb/pb/common"
)

type RegionHandler struct {
	pbCommon.UnimplementedRegionServer
}

// 扒高德数据: https://lbs.amap.com/api/webservice/guide/api/district
func (h *RegionHandler) ManualUpdate(ctx context.Context, req *pbCommon.EmptyRequest) (*pbCommon.EmptyResponse, error) {
	url := "https://restapi.amap.com/v3/config/district"
	key := "2f8d8508e8f34613ef1313ea0e4f2f2a"
	values := make(map[string]interface{})
	values["subdistrict"] = 3
	values["extensions"] = "base"
	values["key"] = key

	ret, err := util.HttpDo("POST", url, values)
	if err != nil {
		return nil, err
	}

	data := &Gaode{}
	err = json.Unmarshal(ret, &data)
	if err != nil {
		return nil, err
	}

	getCityCode := func(v interface{}) string {
		switch v := v.(type) {
		case string:
			return v
		}
		return ""
	}

	for _, v := range data.Districts {
		for _, prov := range v.Districts { // 省
			if prov.Level != "province" {
				continue
			}
			provCode, err := strconv.ParseInt(prov.Adcode, 10, 32)
			if err != nil {
				return nil, err
			}
			region := &model.Region{
				ID:       int32(provCode),
				Name:     prov.Name,
				PID:      10000,
				Level:    model.RegionLevelProvince,
				CityCode: getCityCode(prov.Citycode),
				MerID:    fmt.Sprintf("%d", provCode),
				MerName:  prov.Name,
				Center:   prov.Center,
			}
			id, err := dao.Default.Region.Add(ctx, region)
			if err != nil {
				return nil, err
			}
			fmt.Println("成功添加省：", id)
			for _, city := range prov.Districts { // 市
				if city.Level != "city" {
					continue
				}
				cityCode, err := strconv.ParseInt(city.Adcode, 10, 32)
				if err != nil {
					return nil, err
				}
				region := &model.Region{
					ID:       int32(cityCode),
					Name:     city.Name,
					PID:      int32(provCode),
					Level:    model.RegionLevelCity,
					CityCode: getCityCode(city.Citycode),
					MerID:    fmt.Sprintf("%d,%d", provCode, cityCode),
					MerName:  fmt.Sprintf("%s/%s", prov.Name, city.Name),
					Center:   city.Center,
				}
				id, err := dao.Default.Region.Add(ctx, region)
				if err != nil {
					return nil, err
				}
				fmt.Println("成功添加市：", id)
				for _, dist := range city.Districts { // 区
					if dist.Level != "district" {
						continue
					}
					distCode, err := strconv.ParseInt(dist.Adcode, 10, 32)
					if err != nil {
						return nil, err
					}
					region := &model.Region{
						ID:       int32(distCode),
						Name:     dist.Name,
						PID:      int32(cityCode),
						Level:    model.RegionLevelDistrict,
						CityCode: getCityCode(dist.Citycode),
						MerID:    fmt.Sprintf("%d,%d,%d", provCode, cityCode, distCode),
						MerName:  fmt.Sprintf("%s/%s/%s", prov.Name, city.Name, dist.Name),
						Center:   dist.Center,
					}
					id, err := dao.Default.Region.Add(ctx, region)
					if err != nil {
						return nil, err
					}
					fmt.Println("成功添加区：", id)
				}
			}
		}
	}
	return &pbCommon.EmptyResponse{}, nil
}

func (h *RegionHandler) List(ctx context.Context, req *pbCommon.ListRequest) (*pbCommon.ListRegionResp, error) {
	return &pbCommon.ListRegionResp{}, nil
}

type Gaode struct {
	Status    string      `json:"status"`
	Info      string      `json:"info"`
	Infocode  string      `json:"infocode"`
	Count     string      `json:"count"`
	Districts []Districts `json:"districts"`
}

type Districts struct {
	Citycode  interface{} `json:"citycode"`
	Adcode    string      `json:"adcode"`
	Name      string      `json:"name"`
	Center    string      `json:"center"`
	Level     string      `json:"level"`
	Districts []Districts `json:"districts"`
}
